package command

import (
	"context"
	"fmt"
	"geek_ros/framework/router"
	"github.com/spf13/cobra"
	"net/http"
	"os"
	"os/signal"
	"time"
)

func StartCommand() *cobra.Command {
	command := &cobra.Command{
		Use:   "start",
		Short: "启动服务",
		Long: "启动服务",
		Example: "geekros start",
		Args: func(cmd *cobra.Command, args []string) error {
			return nil
		},
		Run: func(cmd *cobra.Command, args []string) {
			routerHandler := router.Start()
			service := &http.Server{
				Addr:           fmt.Sprintf(":%d", 8181),
				Handler:        routerHandler,
				ReadTimeout:    60 * time.Second,
				WriteTimeout:   60 * time.Second,
				MaxHeaderBytes: 1 << 20,
			}

			go func() {
				if err := service.ListenAndServe(); err != nil {}
			}()

			quit := make(chan os.Signal)
			signal.Notify(quit, os.Interrupt)
			<-quit

			ctx, cancel := context.WithTimeout(context.Background(), 2 * time.Second)

			defer cancel()

			if err := service.Shutdown(ctx); err != nil {}
		},
	}
	return command
}
